import React, { useState, useEffect } from 'react';
import {
  Table,
  Card,
  Input,
  Select,
  Button,
  Space,
  Modal,
  Form,
  message,
  Tag,
  Popconfirm,
  Tooltip,
} from 'antd';
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  LockOutlined,
  UnlockOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { User, UserRole, UserStatus, UserFormData, UserQueryParams, getRolePermissions } from '../types/user';
import {
  getUserList,
  createUser,
  updateUser,
  deleteUser,
  updateUserStatus,
  updateUserRole,
} from '../services/userService';
import dayjs from 'dayjs';

const { Option } = Select;

// 用户角色选项
const roleOptions = [
  { label: '超级管理员', value: UserRole.SUPER_ADMIN },
  { label: '订单管理员', value: UserRole.ORDER_ADMIN },
  { label: '分类管理员', value: UserRole.CATEGORY_ADMIN },
  { label: '商品管理员', value: UserRole.PRODUCT_ADMIN },
];

// 用户状态选项
const statusOptions = [
  { label: '正常', value: UserStatus.ACTIVE },
  { label: '禁用', value: UserStatus.DISABLED },
];

// 获取当前用户角色
const getCurrentUserRole = (): UserRole => {
  // 这里应该从登录状态或全局状态中获取当前用户角色
  // 暂时返回超级管理员角色用于测试
  return UserRole.SUPER_ADMIN;
};

const UserManagement: React.FC = () => {
  // 状态管理
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState<User[]>([]);
  const [total, setTotal] = useState(0);
  const [queryParams, setQueryParams] = useState<UserQueryParams>({
    page: 1,
    pageSize: 10,
  });
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('');
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [form] = Form.useForm();

  // 获取当前用户权限
  const currentUserRole = getCurrentUserRole();
  const currentUserPermissions = getRolePermissions(currentUserRole);

  // 获取用户列表
  const fetchUsers = async () => {
    setLoading(true);
    try {
      const response = await getUserList(queryParams);
      setUsers(response.items);
      setTotal(response.total);
    } catch (error) {
      message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始加载和查询参数变化时重新获取数据
  useEffect(() => {
    fetchUsers();
  }, [queryParams]);

  // 检查是否有权限管理用户
  const canManageUsers = currentUserPermissions.canManageUsers;

  // 如果没有权限，显示提示信息
  if (!canManageUsers) {
    return (
      <Card>
        <div style={{ textAlign: 'center', padding: '50px 0' }}>
          <h2>无权访问</h2>
          <p>您没有权限访问用户管理页面</p>
        </div>
      </Card>
    );
  }

  // 处理搜索和筛选
  const handleSearch = (values: any) => {
    setQueryParams(prev => ({
      ...prev,
      ...values,
      page: 1, // 重置页码
    }));
  };

  // 处理分页变化
  const handleTableChange = (pagination: any) => {
    setQueryParams(prev => ({
      ...prev,
      page: pagination.current,
      pageSize: pagination.pageSize,
    }));
  };

  // 打开新增用户弹窗
  const handleAdd = () => {
    setModalTitle('新增用户');
    setEditingUser(null);
    form.resetFields();
    setModalVisible(true);
  };

  // 打开编辑用户弹窗
  const handleEdit = (user: User) => {
    setModalTitle('编辑用户');
    setEditingUser(user);
    form.setFieldsValue({
      ...user,
      password: undefined, // 编辑时不显示密码
    });
    setModalVisible(true);
  };

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (editingUser) {
        // 编辑用户
        await updateUser(editingUser.id, values);
        message.success('更新用户成功');
      } else {
        // 新增用户
        await createUser(values);
        message.success('创建用户成功');
      }
      setModalVisible(false);
      fetchUsers();
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 处理删除用户
  const handleDelete = async (id: number) => {
    try {
      await deleteUser(id);
      message.success('删除用户成功');
      fetchUsers();
    } catch (error) {
      message.error('删除用户失败');
    }
  };

  // 处理更新用户状态
  const handleStatusChange = async (user: User) => {
    try {
      const newStatus = user.status === UserStatus.ACTIVE ? UserStatus.DISABLED : UserStatus.ACTIVE;
      await updateUserStatus(user.id, newStatus);
      message.success(`用户已${newStatus === UserStatus.ACTIVE ? '启用' : '禁用'}`);
      fetchUsers();
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 处理更新用户角色
  const handleRoleChange = async (user: User, newRole: UserRole) => {
    try {
      await updateUserRole(user.id, newRole);
      message.success('更新用户角色成功');
      fetchUsers();
    } catch (error) {
      message.error('更新用户角色失败');
    }
  };

  // 表格列定义
  const columns: ColumnsType<User> = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      width: 120,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      width: 200,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      width: 120,
    },
    {
      title: '角色',
      dataIndex: 'role',
      width: 150,
      render: (role: UserRole, record: User) => {
        // 只有超级管理员可以修改其他用户的角色
        if (currentUserRole !== UserRole.SUPER_ADMIN) {
          return roleOptions.find(option => option.value === role)?.label;
        }
        return (
          <Select
            value={role}
            style={{ width: 120 }}
            onChange={(value) => handleRoleChange(record, value)}
          >
            {roleOptions.map(option => (
              <Option key={option.value} value={option.value}>
                {option.label}
              </Option>
            ))}
          </Select>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (status: UserStatus) => (
        <Tag color={status === UserStatus.ACTIVE ? 'success' : 'error'}>
          {status === UserStatus.ACTIVE ? '正常' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      width: 180,
      render: (date: string) => dayjs(date).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '最后登录',
      dataIndex: 'lastLoginAt',
      width: 180,
      render: (date: string) => dayjs(date).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 200,
      render: (_, record) => {
        // 不允许修改超级管理员的角色和状态
        const isSuperAdmin = record.role === UserRole.SUPER_ADMIN;
        const canModify = currentUserRole === UserRole.SUPER_ADMIN || !isSuperAdmin;

        return (
          <Space size="middle">
            {canModify && (
              <>
                <Tooltip title="编辑">
                  <Button
                    type="link"
                    icon={<EditOutlined />}
                    onClick={() => handleEdit(record)}
                  />
                </Tooltip>
                <Tooltip title={record.status === UserStatus.ACTIVE ? '禁用' : '启用'}>
                  <Button
                    type="link"
                    icon={record.status === UserStatus.ACTIVE ? <LockOutlined /> : <UnlockOutlined />}
                    onClick={() => handleStatusChange(record)}
                  />
                </Tooltip>
                {!isSuperAdmin && (
                  <Popconfirm
                    title="确定要删除该用户吗？"
                    onConfirm={() => handleDelete(record.id)}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Tooltip title="删除">
                      <Button type="link" danger icon={<DeleteOutlined />} />
                    </Tooltip>
                  </Popconfirm>
                )}
              </>
            )}
          </Space>
        );
      },
    },
  ];

  return (
    <div className="user-management">
      <Card>
        {/* 搜索和筛选区域 */}
        <Form
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 16 }}
        >
          <Form.Item name="keyword">
            <Input
              placeholder="搜索用户名/邮箱/手机号"
              prefix={<SearchOutlined />}
              style={{ width: 200 }}
              allowClear
            />
          </Form.Item>
          <Form.Item name="role">
            <Select
              placeholder="选择角色"
              style={{ width: 150 }}
              allowClear
            >
              {roleOptions.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="status">
            <Select
              placeholder="选择状态"
              style={{ width: 120 }}
              allowClear
            >
              {statusOptions.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
          </Form.Item>
          {currentUserRole === UserRole.SUPER_ADMIN && (
            <Form.Item>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAdd}
              >
                新增用户
              </Button>
            </Form.Item>
          )}
        </Form>

        {/* 用户列表表格 */}
        <Table
          columns={columns}
          dataSource={users}
          rowKey="id"
          loading={loading}
          pagination={{
            current: queryParams.page,
            pageSize: queryParams.pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
          onChange={handleTableChange}
          scroll={{ x: 1300 }}
        />
      </Card>

      {/* 新增/编辑用户弹窗 */}
      <Modal
        title={modalTitle}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{ status: UserStatus.ACTIVE, role: UserRole.PRODUCT_ADMIN }}
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="phone"
            label="手机号"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="password"
            label="密码"
            rules={[
              { required: !editingUser, message: '请输入密码' },
              { min: 6, message: '密码长度不能小于6位' },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            name="role"
            label="角色"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select>
              {roleOptions.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select>
              {statusOptions.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagement; 